<?php
/**
 * @author jim
 * @date 2017/11/25
 */

namespace app\admin\controller;



use app\admin\model\CompanyAuthModel;
use app\admin\model\CompanyManageAccout;
use app\admin\model\FilialePurchaseApplyModel;
use app\admin\model\JsAdminCustomer;
use app\admin\model\InvoiceDetaied;
class Purchase extends Common
{
    // 采购申请列表
    public function applyList()
    {

        $where = array();
        $whereStart = array();
        $whereEnd = array();

        // 定义存储查询条件的数组
        $conditionArr = array();


        // 基本的查询条件
        $where['cpid'] = session('company_id');


        // 列表查询条件
        if (input('sApplyType') && input('sApplyType') > 0) {
            $where['applyType'] = $conditionArr['sApplyType'] = input('sApplyType');
            $this->assign('sApplyType', input('sApplyType'));
        }

        if (input('sStatus')) {
            $sStatus = $conditionArr['sStatus'] = input('sStatus');
            switch ($sStatus) {
                case 1: // 未审核
                    $where['firstApprove'] = 0;
                    break;
                case 2: // 初审通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 0;
                    break;
                case 3: // 初审未通过
                    $where['firstApprove'] = 2;
                    break;
                case 4: // 终审通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 1;
                    break;
                case 5: // 终审未通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 2;
                    break;
                default:

            }


            $this->assign('sStatus', input('sStatus'));
        }

        if (input('sApplyExplain')) {
            $where['applyExplain'] = $conditionArr['sApplyExplain'] = ['like', input('sApplyExplain') . '%'];
            $this->assign('sApplyExplain', input('sApplyExplain'));
        }

        $this->assign('start', input('start'));
        $this->assign('end', input('end'));
        if (input('start')) {
            $conditionArr['start'] = input('start');
            $whereStart['applyTime'] = ['>', input('start') . ' 00:00'];
        }

        if (input('end')) {
            $conditionArr['end'] = input('end');
            $whereEnd['applyTime'] = ['<', input('end') . ' 23:59'];
        }


        $pagesize = config('default_page_size');
        $res = $this->db_app->table('filiale_purchase_apply')
            ->where($where)
            ->where($whereStart)
            ->where($whereEnd)
            ->order('applyTime desc')
            ->paginate($pagesize, false, [
                'query' => $conditionArr
            ]); // 防止参数丢失

//        dump($this->db_app->getLastSql());


        $page = $res->render(); // 分页
        $data = $res->all(); // 数据

//        dump($data);

        $this->assign('page', $page);
        $this->assign('data', $data);

        return $this->fetch();
    }

    // 采购申请
    public function apply()
    {

        if (request()->isPost()) {
            $saveData = array();
            $filialePurchaseApplyModel = new FilialePurchaseApplyModel();

            $saveData['cpid'] = session('company_id');
            $saveData['applyType'] = input('post.applyType');
            $saveData['applyExplain'] = input('post.applyExplain');
            $saveData['collectionAccount'] = input('post.collectionAccount');
            $saveData['payee'] = input('post.payee');
            $saveData['applyMoney'] = input('post.applyMoney');
            $saveData['applyid'] = session('user_id');
            $saveData['applyTime'] = date('Y-m-d H:i:s');
            $saveData['firstApprove'] = 0; // 待审核

            $res = $filialePurchaseApplyModel->addData($saveData);

            $companyManageAccoutModel = new  CompanyManageAccout();
            $companyManageAccoutData = $companyManageAccoutModel->findData(['cpid'=>session('company_id'),'type'=>1,'status'=>1]);

            if($companyManageAccoutData)
            {
                $filialeTodoModel = new  FilialeTodoModel();
                $filialeTodoModel->addData(['cpid'=>session('company_id'),'manageid'=>$companyManageAccoutData['id'],'message'=>'您有采购申请需要审核','gotoUrl'=>'/admin/purchase/checkList','goId'=>$res]);
            }


            if ($res) {
                $this->success('操作成功!', 'purchase/applylist');
            } else {
                $this->error('操作失败!');
            }

        } else {
            // 获取资质认证信息
            $companyAuthModel = new CompanyAuthModel();
            $whereAuth['cpid'] = session('company_id');
            $whereAuth['status'] = 1;

            $authInfo = $companyAuthModel->findData($whereAuth);
            if (empty($authInfo)) {
                $this->error('请先进行资质认证!');
            }

            // 判断身份是否是行政
            if (session('user_type') != 3) {
                $this->error('只有公司行政才可进行此操作!');
            }

            $this->assign('authInfo', $authInfo);
            $this->assign('applyName', session('user_realname'));

            return $this->fetch();
        }

    }

    // 采购申请详情
    public function applyDetail()
    {
        // 获取id
        $id = input('Id');
        $filialePurchaseApplyModel = new FilialePurchaseApplyModel();
        $companyManageAccountModel = new CompanyManageAccout();
        $adminCustomerModel = new JsAdminCustomer();
        $info = $filialePurchaseApplyModel->findData(array('Id' => $id));
        // 获取申请人
        // 获取初审人
        // 获取终审人
        if (!empty($info['applyid'])) {
            $temp = $companyManageAccountModel->findData(array("id" => $info["applyid"]));
            if (!empty($temp)) {
                $info['applyName'] = $temp['realname'];
            }
        }

        if (!empty($info['firstJudge'])) {
            $temp = $companyManageAccountModel->findData(array("id" => $info["firstJudge"]));
            if (!empty($temp)) {
                $info['firstJudgeName'] = $temp['realname'];
            }
        }

        if (!empty($info['finalJudge'])) {
            $temp = $adminCustomerModel->findData(array("id" => $info["finalJudge"]));
            if (!empty($temp)) {
                $info['finalJudgeName'] = $temp['name'];
            }
        }

        $this->assign('info', $info);


        return $this->fetch();
    }


    // 采购申请详情
    public function applyDetailUpPic()
    {
        // 获取id
        $id = input('Id');
        $filialePurchaseApplyModel = new FilialePurchaseApplyModel();
        $companyManageAccountModel = new CompanyManageAccout();
        $adminCustomerModel = new JsAdminCustomer();
        $info = $filialePurchaseApplyModel->findData(array('Id' => $id));
        // 获取申请人
        // 获取初审人
        // 获取终审人
        if (!empty($info['applyid'])) {
            $temp = $companyManageAccountModel->findData(array("id" => $info["applyid"]));
            if (!empty($temp)) {
                $info['applyName'] = $temp['realname'];
            }
        }

        if (!empty($info['firstJudge'])) {
            $temp = $companyManageAccountModel->findData(array("id" => $info["firstJudge"]));
            if (!empty($temp)) {
                $info['firstJudgeName'] = $temp['realname'];
            }
        }

        if (!empty($info['finalJudge'])) {
            $temp = $adminCustomerModel->findData(array("id" => $info["finalJudge"]));
            if (!empty($temp)) {
                $info['finalJudgeName'] = $temp['name'];
            }
        }

        $invoiceDetaiedModel = new  InvoiceDetaied();
        $invoiceDetaiedData = $invoiceDetaiedModel->selectData(['applyid' => $id]);


        $this->assign('resId', $id);
        $this->assign('invoiceList', $invoiceDetaiedData);
        $this->assign('info', $info);


        return $this->fetch();
    }


    // 初审列表
    public function checkList()
    {

        $where = array();
        $whereStart = array();
        $whereEnd = array();

        // 定义存储查询条件的数组
        $conditionArr = array();


        // 基本的查询条件
        $where['cpid'] = session('company_id');


        // 列表查询条件
        if (input('sApplyType') && input('sApplyType') > 0) {
            $where['applyType'] = $conditionArr['sApplyType'] = input('sApplyType');
            $this->assign('sApplyType', input('sApplyType'));
        }

        if (input('sStatus')) {
            $sStatus = $conditionArr['sStatus'] = input('sStatus');
            switch ($sStatus) {
                case 1: // 未审核
                    $where['firstApprove'] = 0;
                    break;
                case 2: // 初审通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 0;
                    break;
                case 3: // 初审未通过
                    $where['firstApprove'] = 2;
                    break;
                case 4: // 终审通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 1;
                    break;
                case 5: // 终审未通过
                    $where['firstApprove'] = 1;
                    $where['finalApprove'] = 2;
                    break;
                default:

            }


            $this->assign('sStatus', input('sStatus'));
        }

        if (input('sApplyExplain')) {
            $where['applyExplain'] = $conditionArr['sApplyExplain'] = ['like', input('sApplyExplain') . '%'];
            $this->assign('sApplyExplain', input('sApplyExplain'));
        }

        $this->assign('start', input('start'));
        $this->assign('end', input('end'));
        if (input('start')) {
            $conditionArr['start'] = input('start');
            $whereStart['applyTime'] = ['>', input('start') . ' 00:00'];
        }

        if (input('end')) {
            $conditionArr['end'] = input('end');
            $whereEnd['applyTime'] = ['<', input('end') . ' 23:59'];
        }


        $pagesize = config('default_page_size');
        $res = $this->db_app->table('filiale_purchase_apply')
            ->where($where)
            ->where($whereStart)
            ->where($whereEnd)
            ->order('applyTime desc')
            ->paginate($pagesize, false, [
                'query' => $conditionArr
            ]); // 防止参数丢失


//        dump($this->db_app->getLastSql());


        $page = $res->render(); // 分页
        $data = $res->all(); // 数据

        $companyManageAccount = new CompanyManageAccout();
        foreach ($data as $k => $v) {
            $tempAccount = $companyManageAccount->findData(array('id' => $v['firstJudge']));
            $data[$k]['firstJudgeName'] = $tempAccount['realname'];
        }


        $this->assign('page', $page);
        $this->assign('data', $data);

        return $this->fetch();
    }

    // 初审采购
    public function check()
    {
        if ($_POST['Id']) {
            // 表单提交
            $Id = input('post.Id');
            $filialePurchaseApplyModel = new FilialePurchaseApplyModel();
            $data['firstJudge'] = session('user_id');
            $data['firstTime'] = date('Y-m-d H:i:s', time());
            $data['firstOpinion'] = input('post.firstOpinion') ? input('post.firstOpinion') : "无";
            $data['firstApprove'] = input('post.firstApprove');

            $filialePurchaseApplyModel->editData(array('Id' => $Id), $data);


            $filialeTodoModel = new  FilialeTodoModel();
            $filialeTodoModel->editData(['goId'=>$Id],['state'=>1]);
            $this->redirect('purchase/checklist');

        } else {
            // 判断身份是否是行政
            if (session('user_type') != 1) {
                $this->error('只有公司CEO才可进行此操作!');
            }

            // 获取id
            $Id = input('Id');

            $filialePurchaseApplyModel = new FilialePurchaseApplyModel();
            $companyManageAccountModel = new CompanyManageAccout();
            $info = $filialePurchaseApplyModel->findData(array('Id' => $Id));
            // 获取申请人
            if (!empty($info['applyid'])) {
                $temp = $companyManageAccountModel->findData(array("id" => $info["applyid"]));
                if (!empty($temp)) {
                    $info['applyName'] = $temp['realname'];
                }
            }


            $info['firstJudge'] = session('user_id');
            $info['firstJudgeName'] = session('user_realname');

            $this->assign('info', $info);

            return $this->fetch();
        }

    }

    //添加发票照片
    public function insertapplypicinvoice()
    {
        $InvoiceDetaiedModel = new  InvoiceDetaied();
        $goodsData = json_decode($_POST['goodsDataJson'], true);
        $Id = $_POST['id'];
        foreach ($goodsData as $val) {
            $picid = $val['Id'];
            if ($val['Type'] == 'delete') {
                $InvoiceDetaiedModel->delData(['Id' => $picid]);
            } else {
                $data = [];
                $data['cpid'] = session('company_id');
                $data['applyid'] = $Id;
                $data['money'] = $val['invoiceMoney'];
                $data['url'] = $val['upImgUrl'];
                if ($picid) {
                    $InvoiceDetaiedModel->editData(['Id' => $picid], $data);
                } else {
                    $InvoiceDetaiedModel->addData($data);
                }
            }
        }
    }
}